<template>
  <div class="select-seat-container">
    <Header v-if="currentShowInfo" :info="currentShowInfo"></Header>
    <SeatDemos v-if="options.loadComplete" :list="options.seatTypeList"></SeatDemos>
    <AreaDemos v-if="currentAreaList" :list="currentAreaList"></AreaDemos>
    <SeatView v-if="currentShowInfo" :arealist="currentAreaList ? currentAreaList : []" :options="options"
      @onchange="clickSeat"></SeatView>
    <Footer v-if="currentShowInfo && currentFilmInfo" :film-info="currentFilmInfo" :selected-seat="options.selectedSeat"
      :show-info="currentShowInfo" :arealist="currentAreaList ? currentAreaList : []" @onCloseItem="onCloseItem"></Footer>
  </div>
</template>
<script lang="ts">
import { needLogin } from "../../utils/needLoginHook";
export default {
  name: "SelectSeat",
  mixins: [needLogin],
};
</script>
<script setup lang="ts">
import Taro from "@tarojs/taro";
import Header from "./header.vue";
import SeatDemos from "./seat-demos.vue";
import AreaDemos from "./area-demos.vue";
import SeatView from "./seat-view.vue";
import Footer from "./footer.vue";
import { onMounted, ref } from "vue";
import * as seatConfig from "./seat_config";
import * as cinemaApi from "../../api/cinema";
const router = Taro.useRouter();
const currentShowId: any = ref("");
const currentShowInfo: any = ref(null);
const currentFilmInfo: any = ref(null);
const currentAreaList: any = ref(null);
const options: any = ref({
  seatList: [],
  selectedSeat: [],
  hallName: undefined,
  scaleValue: 1,
  hidden: "hidden",
  maxSelect: 4,
  totalPrice: 0,
  loadComplete: false,
  timer: null,
  seatArea: 0,
  seatTypeList: [],
  rpxToPx: 0,
  maxY: 0,
  maxX: 0,
  seatScale: 0,
  seatScaleHeight: 0,
  seatToolArr: [],
});
onMounted(() => {
  console.log(router.params.showid);
  currentShowId.value = router.params.showid;
  getAppInfo();
  getData();
});
const getData = async () => {
  Taro.showLoading({
    title: "加载座位信息",
  });
  try {
    const data = {
      showid: currentShowId.value,
    };
    const res: any = await cinemaApi.seat(data);
    currentShowInfo.value = res.show_info;
    currentFilmInfo.value = res.film_info;
    if (res.show_info.area_price) {
      currentAreaList.value = JSON.parse(res.show_info.area_price);
    }
    const seats = formatSeatsData(res.seat_data.seats);
    initSeatArea(seats);
    Taro.hideLoading();
  } catch (error) {
    Taro.hideLoading();
    Taro.showToast({
      title: "本场次已结束",
      icon: "error",
      duration: 2000,
      success: () => {
        setTimeout(() => {
          Taro.navigateBack();
        }, 1000);
      },
    });
  }
};
// 整理远程座位数据格式
const formatSeatsData = (data) => {
  const arr = data.map((item: any) => {
    const res = {
      id: item.seatId,
      row: String(item.rowNo),
      col: String(item.columnNo),
      gRow: item.rowNo,
      gCol: item.columnNo,
      type: "0-2",
      flag: "0",
      price: "0",
      seatNo: item.seatNo,
      areaId: item.areaId,
      lovestatus: item.lovestatus,
    };
    if (item.status === "N" && item.lovestatus === 0) {
      res.type = "0";
    } else if (item.status === "LK" && item.lovestatus === 0) {
      res.type = "0-2";
    } else if (item.status === "N" && item.lovestatus === 1) {
      res.type = "1";
    } else if (item.status === "LK" && item.lovestatus === 1) {
      res.type = "1-2";
    } else if (item.status === "N" && item.lovestatus === 2) {
      res.type = "2";
    } else if (item.status === "LK" && item.lovestatus === 2) {
      res.type = "2-2";
    }
    return res;
  });
  return arr;
};
// 获取系统信息
const getAppInfo = () => {
  const systemInfo: any = Taro.getSystemInfoSync();
  const seatArea =
    systemInfo.screenHeight -
    systemInfo.statusBarHeight -
    (500 * systemInfo.screenWidth) / 750;
  options.value.seatArea = seatArea;
  options.value.rpxToPx = systemInfo.screenWidth / 750;
};
const onCloseItem = (id) => {
  let seatList = options.value.seatList;
  const index = seatList.findIndex((item) => {
    return id === item.id;
  });
  console.log(index);

  processSelected(index);
};
const initSeatArea = (seats) => {
  const showInfo = currentShowInfo.value;
  const seatTypeList = seatConfig.seatTypeList;
  const seatList = prosessSeatList(seats, seatTypeList);
  options.value.hallName = showInfo.hall_name;
  options.value.seatTypeList = seatTypeList;
  options.value.seatList = seatList;
  options.value.selectedSeat = [];
  options.value.totalPrice = 0;
  options.value.hidden = "hidden";
  //计算X和Y坐标最大值
  prosessMaxSeat(seatList);
  //计算左侧座位栏的数组
  seatToolArr();
  //按每排生成座位数组对象
  creatSeatMap();
  //确认最佳坐标座位
  creatBestSeat();
};

const prosessSeatList = (seatList, seatTypeList) => {
  let resSeatList = seatList;
  resSeatList.forEach((element) => {
    // 获取座位的类型的首字母
    let firstNumber = element.type.substr(0, 1);
    // 在原来的对象中加入两个属性  otherLoveSeatIndex 对应情侣座位的原数组下标 otherLoveSeatId  对应情侣座位的Id
    element.otherLoveSeatIndex = null;
    element.otherLoveSeatId = null;
    // 座位的类型的首字母为 '1' 是情侣首座 处理情侣首座位
    if (firstNumber === "1") {
      for (const index in resSeatList) {
        if (
          resSeatList[index].gRow === element.gRow &&
          resSeatList[index].gCol === element.gCol + 1
        ) {
          element.otherLoveSeatIndex = index;
          element.otherLoveSeatId = resSeatList[index].id;
        }
      }
    }
    // 座位的类型的首字母为 '2' 是情侣次座 处理情侣次座位
    if (firstNumber === "2") {
      for (const index in resSeatList) {
        if (
          resSeatList[index].gRow === element.gRow &&
          resSeatList[index].gCol === element.gCol - 1
        ) {
          element.otherLoveSeatIndex = index;
          element.otherLoveSeatId = resSeatList[index].id;
        }
      }
    }
    // 加载座位的图标
    let seatType = seatTypeList;
    for (const key in seatType) {
      // 加载每个座位的初始图标defautIcon 和 当前图标 nowIcon
      if (element.type === seatType[key].type) {
        element.nowIcon = seatType[key].icon;
        element.defautIcon = seatType[key].icon;
      }
      // 根据首字母找到对应的被选中图标
      if (firstNumber + "-1" === seatType[key].type) {
        element.selectedIcon = seatType[key].icon;
      }
      // 根据首字母找到对应的被选中图标
      if (firstNumber + "-2" === seatType[key].type) {
        element.soldedIcon = seatType[key].icon;
      }
      // 根据首字母找到对应的被选中图标
      if (firstNumber + "-3" === seatType[key].type) {
        element.fixIcon = seatType[key].icon;
      }
    }
    // 如果座位是已经售出 和 维修座位 加入属性canClick 判断座位是否可以点击
    if (
      element.defautIcon === element.soldedIcon ||
      element.defautIcon === element.fixIcon
    ) {
      element.canClick = false;
    } else {
      element.canClick = true;
    }
  });
  return resSeatList;
};
//计算最大座位数,生成影厅图大小
const prosessMaxSeat = (value) => {
  let seatList = value;
  let maxY: any = 0;
  for (let i = 0; i < seatList.length; i++) {
    let tempY = seatList[i].gRow;
    if (parseInt(tempY) > parseInt(maxY)) {
      maxY = tempY;
    }
  }
  let maxX: any = 0;
  for (var i = 0; i < seatList.length; i++) {
    var tempX = seatList[i].gCol;
    if (parseInt(tempX) > parseInt(maxX)) {
      maxX = tempX;
    }
  }
  let seatRealWidth = parseInt(maxX) * 70 * options.value.rpxToPx;
  let seatRealheight = parseInt(maxY) * 70 * options.value.rpxToPx;
  let seatScale = 1;
  let seatScaleX = 1;
  let seatScaleY = 1;
  let seatAreaWidth = 630 * options.value.rpxToPx;
  let seatAreaHeight = options.value.seatArea - 200 * options.value.rpxToPx;
  if (seatRealWidth > seatAreaWidth) {
    seatScaleX = seatAreaWidth / seatRealWidth;
  }
  if (seatRealheight > seatAreaHeight) {
    seatScaleY = seatAreaHeight / seatRealheight;
  }
  if (seatScaleX < 1 || seatScaleY < 1) {
    seatScale = seatScaleX < seatScaleY ? seatScaleX : seatScaleY;
  }
  options.value.maxY = parseInt(maxY);
  options.value.maxX = parseInt(maxX);
  options.value.seatScale = seatScale;
  options.value.seatScaleHeight = seatScale * 70 * options.value.rpxToPx;
};
// 座位左边栏的数组
const seatToolArr = () => {
  let seatToolArr: any = [];
  let yMax = options.value.maxY;
  let seatList: any = options.value.seatList;
  for (let i = 1; i <= yMax; i++) {
    let el: any = "";
    for (let j = 0; j < seatList.length; j++) {
      if (parseInt(seatList[j].gRow) === i) {
        el = seatList[j].row;
      }
    }
    seatToolArr.push(el);
  }
  options.value.seatToolArr = seatToolArr;
};
// 根据seatList 生成一个类map的对象 key值为gRow坐标 value值为gRow为key值的数组
const creatSeatMap = () => {
  let seatList: any = options.value.seatList;
  var obj = {};
  for (let index in seatList) {
    let seatRowList = seatList[index].gRow;
    if (seatRowList in obj) {
      // 原本数组下标
      seatList[index].orgIndex = index;
      obj[seatRowList].push(seatList[index]);
    } else {
      let seatArr: any = [];
      // 原本数组下标
      seatList[index].orgIndex = index;
      seatArr.push(seatList[index]);
      obj[seatRowList] = seatArr;
    }
  }
  options.value.seatMap = obj;
};
//生成最佳座位
const creatBestSeat = () => {
  // 优先左侧
  const bestX = parseInt(options.value.maxX) / 2 + 1;
  // 四舍五入  0.618为黄金分割比例
  const bestY = Math.round(options.value.maxY * 0.618);
  options.value.bestX = bestX;
  options.value.bestY = bestY;
  options.value.loadComplete = true;
};
// 点击每个座位触发的函数
const clickSeat = (event) => {
  let index = event.currentTarget.dataset.index;
  if (options.value.seatList[index].canClick) {
    if (
      options.value.seatList[index].nowIcon ===
      options.value.seatList[index].selectedIcon
    ) {
      processSelected(index);
    } else {
      processUnSelected(index);
    }
  }
  if (options.value.selectedSeat.length == 0) {
    options.value.hidden = "hidden";
  }

  let _selectedSeatList = options.value.selectedSeat;
  let totalPrice = 0;
  for (const key in _selectedSeatList) {
    let price = parseInt(_selectedSeatList[key].price);
    totalPrice += price;
  }
  options.value.totalPrice = totalPrice;
};
// 处理已选的座位
const processSelected = (index) => {
  let _selectedSeatList = options.value.selectedSeat;
  let seatList = options.value.seatList;
  let otherLoveSeatIndex = seatList[index].otherLoveSeatIndex;
  if (otherLoveSeatIndex !== null) {
    // 如果是情侣座位
    // 改变这些座位的图标为初始图标
    seatList[index].nowIcon = seatList[index].defautIcon;
    seatList[otherLoveSeatIndex].nowIcon =
      seatList[otherLoveSeatIndex].defautIcon;
    for (const key in _selectedSeatList) {
      // 移除id一样的座位
      if (_selectedSeatList[key].id === seatList[index].id) {
        _selectedSeatList.splice(key, 1);
      }
    }
    // 移除对应情侣座位
    for (const key in _selectedSeatList) {
      if (_selectedSeatList[key].id === seatList[otherLoveSeatIndex].id) {
        _selectedSeatList.splice(key, 1);
      }
    }
  } else {
    // 改变这些座位的图标为初始图标 并 移除id一样的座位
    seatList[index].nowIcon = seatList[index].defautIcon;
    for (const key in _selectedSeatList) {
      if (_selectedSeatList[key].id === seatList[index].id) {
        _selectedSeatList.splice(key, 1);
      }
    }
  }
  options.value.selectedSeat = _selectedSeatList;
  options.value.seatList = seatList;
};
// 处理未选择的座位
const processUnSelected = (index) => {
  let _selectedSeatList = options.value.selectedSeat;
  let seatList = options.value.seatList;
  let otherLoveSeatIndex = seatList[index].otherLoveSeatIndex;
  if (otherLoveSeatIndex !== null) {
    // 如果选中的是情侣座位 判断选择个数不大于 maxSelect
    if (_selectedSeatList.length >= options.value.maxSelect - 1) {
      return;
    }
    // 改变这些座位的图标为已选择图标
    seatList[index].nowIcon = seatList[index].selectedIcon;
    seatList[otherLoveSeatIndex].nowIcon =
      seatList[otherLoveSeatIndex].selectedIcon;
    // 记录 orgIndex属性 是原seatList数组中的下标值
    seatList[index].orgIndex = index;
    seatList[otherLoveSeatIndex].orgIndex = otherLoveSeatIndex;
    // 把选择的座位放入到已选座位数组中
    let temp = { ...seatList[index] };
    let tempLove = { ...seatList[otherLoveSeatIndex] };
    _selectedSeatList.push(temp);
    _selectedSeatList.push(tempLove);
  } else {
    // 如果选中的是非情侣座位 判断选择个数不大于 maxSelect
    if (_selectedSeatList.length >= options.value.maxSelect) {
      Taro.showToast({
        title: "最多只能选择" + options.value.maxSelect + "个座位哦~",
        icon: "none",
        duration: 2000,
      });
      return;
    }
    // 改变这些座位的图标为已选择图标
    seatList[index].nowIcon = seatList[index].selectedIcon;
    // 记录 orgIndex属性 是原seatList数组中的下标值
    seatList[index].orgIndex = index;
    // 把选择的座位放入到已选座位数组中
    let temp = { ...seatList[index] };
    _selectedSeatList.push(temp);
  }
  options.value.selectedSeat = _selectedSeatList;
  options.value.seatList = seatList;
  options.value.hidden = "";
};
</script>
<style lang="scss">
.select-seat-container {
  display: flex;
  flex-direction: column;
}

/*
*页面最下方确认选座区域
*/

.orderComfirm {
  background: #fff;
  position: fixed;
  display: flex;
  bottom: 0rpx;
  width: 100%;
  line-height: 100rpx;
  z-index: 3;
}

/*
*页面最下方价格区域
*/

.orderPrice {
  text-indent: 30rpx;
  color: black;
  height: 100rpx;
  width: 60%;
}

/*
*页面最下方价格字体样式
*/

.orderPrice text {
  color: red;
}

/*
*页面最下方确认选座区域渐变色
*/

.comfirm {
  font-weight: 900;
  text-align: center;
  color: white;
  width: 100%;
  background: linear-gradient(to right, #c26dfe, #6f50f5);
  height: 100rpx;
}

/*
*用户选中的座位区域
*/

.selectSeatInfo {
  background: #fff;
  position: fixed;
  bottom: 100rpx;
  height: 80rpx;
  width: 100%;
  padding: 10rpx 0;
}

/*
*用户选中的座位详情滑块
*/

.scrollSeat {
  height: 90rpx;
  white-space: nowrap;
}

/*
*每块用户选中的座位详情
*/

.scrollItem {
  border: 1rpx solid #bbb;
  border-radius: 10rpx;
  width: 180rpx;
  display: inline-block;
  margin-left: 20rpx;
  position: relative;
}

/*
* 快速选座模块
*/

.quickItem {
  border: 1rpx solid #bbb;
  color: #aaa;
  font-size: 28rpx;
  border-radius: 10rpx;
  width: 160rpx;
  height: 75rpx;
  line-height: 75rpx;
  text-align: center;
  display: inline-block;
  margin-left: 20rpx;
  position: relative;
}

/*
*每块用户选中的座位详情上方文字
*/

.scrollTextTop {
  color: #555;
  text-indent: 30rpx;
  line-height: 25rpx;
  font-size: 26rpx;
  height: 25rpx;
  margin-top: 10rpx;
}

/*
*每块用户选中的座位详情下方文字
*/

.scrollTextBottom {
  font-weight: 600;
  font-size: 26rpx;
  color: #ff005a;
  text-indent: 40rpx;
  height: 25rpx;
  line-height: 25rpx;
  margin: 10rpx 0;
}

/*
*每块用户选中的座位详情关闭按钮
*/

.scrollItem image {
  position: absolute;
  z-index: 2;
  width: 30rpx;
  height: 30rpx;
  right: 10rpx;
  top: 50%;
  transform: translateY(-50%);
}

.seatAreaTip {
  position: relative;
  width: 750rpx;
  height: 50rpx;
  line-height: 50rpx;
  text-align: center;
  font-size: 16rpx;
  color: rgba(0, 0, 0, 0.1);
  border-top: 1rpx dashed rgba(0, 0, 0, 0.1);
}
</style>
